package org.systemsbiology.rface.hadoop;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.systemsbiology.hadoop.ioformats.FileAwareTextInputFormat;
import org.systemsbiology.hadoop.ioformats.LexicalKey;
import org.systemsbiology.rface.hadoop.data.ResultGroup;
import org.systemsbiology.rface.hadoop.data.StatAggregation;
import org.systemsbiology.rface.hadoop.mappers.ResultFromFileLine;
import org.systemsbiology.rface.hadoop.reducers.CalculateStatistics;
import org.systemsbiology.rface.hadoop.reducers.CombineResultGroups;

import java.io.File;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: anorberg
 * Date: 10/20/11
 * Time: 4:16 PM
 *
 * Main class for RF-ACE Aggregator.
 */
public class Main extends Configured implements Tool{

    public static final String INTERESTING_FILES_KEY = "InterestingFiles";

    public static void main(String args[]) throws Exception{
        Logger.getLogger(Main.class.getName()).info("RF-ACE Aggregator result: " + ToolRunner.run(new Configuration(), new Main(), args));
    }

    public int run(String[] strings) throws Exception {
        if(strings.length != 3){
            throw new IllegalArgumentException("Wrong number of parameters- must have BASEFILES-LIST, TARGFILES-LIST, OUTFILE");
        }

        Configuration conf = new Configuration(getConf());
        conf.set(INTERESTING_FILES_KEY, strings[1]);

        Job job = new Job(conf, getClass().getName());
        job.setJarByClass(getClass());
        job.setMapperClass(ResultFromFileLine.class);
        job.setReducerClass(CalculateStatistics.class);
        job.setCombinerClass(CombineResultGroups.class);
        job.setInputFormatClass(FileAwareTextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setOutputKeyClass(LexicalKey.class);
        job.setOutputValueClass(StatAggregation.class);
        job.setMapOutputKeyClass(LexicalKey.class);
        job.setMapOutputValueClass(ResultGroup.class);

        String[] baseFiles = strings[0].split(Pattern.quote(File.pathSeparator));
        for(String path : baseFiles){
            FileInputFormat.addInputPath(job, new Path(path));
        }

        baseFiles = strings[1].split(Pattern.quote(File.pathSeparator));
        for(String path : baseFiles){
            FileInputFormat.addInputPath(job, new Path(path));
        }

        FileOutputFormat.setOutputPath(job, new Path(strings[2]));

        return job.waitForCompletion(true) ? 0 : 1;
    }
}
